package com.css.fxfzysx.modules.vaolEngineering.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.constants.FxfzConstants;
import com.css.fxfzysx.modules.cztDataMange.result.ParsingResult;
import com.css.fxfzysx.modules.lifeline.annotation.ValidationProcessor;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxMainTableEntity;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxTransformerSubstationEntity;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxVersionEntity;
import com.css.fxfzysx.modules.lifeline.repository.LifelineEngineeringRepository;
import com.css.fxfzysx.modules.lifeline.utils.ShpUtils;
import com.css.fxfzysx.modules.lifeline.vo.basic.DestructiveStateVo;
import com.css.fxfzysx.modules.vaolEngineering.entity.CtVulnerabilityEntity;
import com.css.fxfzysx.modules.vaolEngineering.entity.newEntity.SmxTransformerSubstationValueEntity;
import com.css.fxfzysx.modules.vaolEngineering.param.update.TsParam;
import com.css.fxfzysx.modules.vaolEngineering.param.update.TsValueParam;
import com.css.fxfzysx.modules.vaolEngineering.repository.TsVulnerabilityRepository;
import com.css.fxfzysx.modules.vaolEngineering.service.TsVulnerabilityService;
import com.css.fxfzysx.modules.vaolEngineering.utils.CheckUtil;
import com.css.fxfzysx.modules.vaolEngineering.utils.MainTableUtils;
import com.css.fxfzysx.modules.vaolEngineering.vo.importVo.CtVulnerabilityImportVo;
import com.css.fxfzysx.modules.vaolEngineering.vo.lifelineCalculation.SmxTransformerSubstationValueVo;
import com.css.fxfzysx.util.PlatformDateUtils;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.css.fxfzysx.util.ShpAnalyticUtil;
import com.css.fxfzysx.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TsVulnerabilityServiceImpl implements TsVulnerabilityService {

    @Autowired
    private TsVulnerabilityRepository tsVulnerabilityRepository;

    @Autowired
    private LifelineEngineeringRepository lifelineEngineeringRepository;

    @Autowired
    private MainTableUtils mainTableUtils;

    @Autowired
    private ShpUtils shpUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse caTsVulnerability(String versionId, String id) {
        List<SmxTransformerSubstationEntity> tsList;
        if (PlatformObjectUtils.isNotEmpty(id)) {
            tsVulnerabilityRepository.delValueByTsId(id);
            tsList = tsVulnerabilityRepository.getByTableId(id);
        } else {
            tsList = tsVulnerabilityRepository.getByVersionId(versionId);
        }
        Map<String, List<SmxTransformerSubstationEntity>> provinceCollect = tsList.stream().collect(Collectors.groupingBy(SmxTransformerSubstationEntity::getProvince));

        for (Map.Entry<String, List<SmxTransformerSubstationEntity>> entry : provinceCollect.entrySet()) {
            List<SmxTransformerSubstationEntity> list = entry.getValue();
            //将各元件的pga从小到达排序
            list.sort(Comparator.comparing(SmxTransformerSubstationEntity::getPga));
            list.forEach(it -> {
                BigDecimal pga = it.getPga();
                if (BigDecimal.valueOf(0.04).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.09)) < 0) {
                    it.setRange(6);
                }
                if (BigDecimal.valueOf(0.09).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.19)) < 0) {
                    it.setRange(7);
                }
                if (BigDecimal.valueOf(0.19).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.38)) < 0) {
                    it.setRange(8);
                }
                if (BigDecimal.valueOf(0.38).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.75)) < 0) {
                    it.setRange(9);
                }
                if (pga.compareTo(BigDecimal.valueOf(0.75)) > -1) {
                    it.setRange(10);
                }
            });

            Map<Integer, List<SmxTransformerSubstationEntity>> ctVulnerabilityMap = list.stream()
                    .collect(Collectors.groupingBy(SmxTransformerSubstationEntity::getRange));

            Map<Integer, List<SmxTransformerSubstationEntity>> collect = new HashMap<>();
            int counter = 1;
            for (List<SmxTransformerSubstationEntity> value : ctVulnerabilityMap.values()) {
                collect.put(counter++, value);
            }
            if (collect.size() < 3) {
                return RestResponse.fail("失败!区间必须大于等于3");
            }

            ArrayList<SmxTransformerSubstationValueEntity> resultList = new ArrayList<>();
            for (Map.Entry<Integer, List<SmxTransformerSubstationEntity>> dataList : collect.entrySet()) {
                SmxTransformerSubstationValueEntity entity = new SmxTransformerSubstationValueEntity();
                List<SmxTransformerSubstationEntity> value = dataList.getValue();
                //区间内的样本总数
                int intervalZone = value.stream().mapToInt(SmxTransformerSubstationEntity::getSamplesNumber).sum();
                int damagesNumber = value.stream().mapToInt(SmxTransformerSubstationEntity::getDamagesNumber).sum();
                BigDecimal pag = BigDecimal.valueOf(0);
                for (int i = 0; i < value.size(); i++) {
                    BigDecimal pgai = BigDecimal.valueOf(0);
                    for (int j = 1; j <= value.size(); j++) {
                        pgai = BigDecimal.valueOf(value.get(i).getSamplesNumber()).multiply(value.get(i).getPga());
                    }
                    pag = pag.add(pgai);
                }
                BigDecimal resultPgai = pag.divide(new BigDecimal(intervalZone), 4, RoundingMode.UP);
                //N
                int N = 0;
                for (int i = dataList.getKey(); i <= collect.size(); i++) {
                    N += collect.get(i).stream().mapToInt(SmxTransformerSubstationEntity::getSamplesNumber).sum();
                }
                entity.setRange(dataList.getValue().get(0).getRange());
                entity.setPgai(resultPgai);
                entity.setSamplesAcc(N);
                entity.setSiteNum(value.size());
                entity.setRangeCount(intervalZone);
                entity.setRangeBreakCount(damagesNumber);
                resultList.add(entity);
            }

            for (int i = 0; i < resultList.size(); i++) {
                //存活概率   r(i)
                BigDecimal i1 = BigDecimal.valueOf(resultList.get(i).getRangeBreakCount())
                        .divide(BigDecimal.valueOf(resultList.get(i).getSamplesAcc()), 4, RoundingMode.HALF_UP);
                BigDecimal r = BigDecimal.valueOf(1).subtract(i1);
                resultList.get(i).setRil(r.setScale(4, RoundingMode.HALF_UP));

                //累积失效概率  R
                if (i == 0) {
                    resultList.get(i).setRir(resultList.get(i).getRil().setScale(4, RoundingMode.HALF_UP));
                } else {
                    resultList.get(i).setRir(resultList.get(i).getRil()
                            .multiply(resultList.get(i - 1).getRir()).setScale(4, RoundingMode.HALF_UP));
                }
                //累计失效概率  F
                resultList.get(i).setFi(BigDecimal.valueOf(1).subtract(resultList.get(i).getRir()).setScale(4, RoundingMode.HALF_UP));
                resultList.get(i).setFiCorrect(BigDecimal.valueOf(1).subtract(resultList.get(i).getRir()).setScale(4, RoundingMode.HALF_UP));
            }
            for (SmxTransformerSubstationValueEntity entity : resultList) {
                String tableId = list.get(0).getTableId();
                entity.setId(UUIDGenerator.getUUID());
                entity.setTsId(tableId);
                entity.setDelFlag("0");
                tsVulnerabilityRepository.saveTsResult(entity);
                String year = mainTableUtils.getKeyByValue("smxjsnd", MainTableUtils.getYear(list.get(0).getYear()));
                DestructiveStateVo stateVo = tsVulnerabilityRepository.getByBasicInfo(list.get(0),year);
                mainTableUtils.updateCalculationStatus(tableId,stateVo.getDisasterRate6State(),stateVo.getDisasterRate7State(),stateVo.getDisasterRate8State(),stateVo.getDisasterRate9State(),stateVo.getDisasterRate10State(), 1);
            }
        }
        mainTableUtils.updateVersionCalculationStatus(versionId, 0);
        return RestResponse.succeed("计算成功");
    }

    @Override
    public RestResponse groupTsVulnerability(List<CtVulnerabilityEntity> ctVulnerabilityList) {
        try {
            HashMap<Integer, Object> resultMap = new HashMap<>();
            //将各元件的pga从小到达排序
            ctVulnerabilityList.sort(Comparator.comparing(CtVulnerabilityEntity::getAccelerationMax));
            ctVulnerabilityList.forEach(it -> {
                BigDecimal accelerationMax = it.getAccelerationMax();
                if (BigDecimal.valueOf(0.04).compareTo(accelerationMax) < 1 && accelerationMax.compareTo(BigDecimal.valueOf(0.09)) < 0) {
                    it.setRange(6);
                }
                if (BigDecimal.valueOf(0.09).compareTo(accelerationMax) < 1 && accelerationMax.compareTo(BigDecimal.valueOf(0.19)) < 0) {
                    it.setRange(7);
                }
                if (BigDecimal.valueOf(0.19).compareTo(accelerationMax) < 1 && accelerationMax.compareTo(BigDecimal.valueOf(0.39)) < 0) {
                    it.setRange(8);
                }
                if (BigDecimal.valueOf(0.39).compareTo(accelerationMax) < 1 && accelerationMax.compareTo(BigDecimal.valueOf(0.79)) < 0) {
                    it.setRange(9);
                }
                if (accelerationMax.compareTo(BigDecimal.valueOf(0.79)) > -1) {
                    it.setRange(10);
                }
            });

            Map<Integer, List<CtVulnerabilityEntity>> CtVulnerabilityMap = ctVulnerabilityList.stream()
                    .collect(Collectors.groupingBy(CtVulnerabilityEntity::getRange));

            Map<Integer, List<CtVulnerabilityEntity>> collect = new HashMap<>();
            int counter = 1;
            for (List<CtVulnerabilityEntity> list : CtVulnerabilityMap.values()) {
                collect.put(counter++, list);
            }
            if (collect.size() < 3) {
                return RestResponse.fail("失败!区间必须大于等于3");
            }
            for (Map.Entry<Integer, List<CtVulnerabilityEntity>> dataList : collect.entrySet()) {
                HashMap<String, Object> map = new HashMap<>();
                List<CtVulnerabilityEntity> value = dataList.getValue();
                //区间内的样本总数
                int intervalZone = value.stream().mapToInt(CtVulnerabilityEntity::getSampleNum).sum();
                BigDecimal pag = BigDecimal.valueOf(0);
                for (int i = 0; i < value.size(); i++) {
                    BigDecimal pgai = BigDecimal.valueOf(0);
                    for (int j = 1; j <= value.size(); j++) {
                        pgai = BigDecimal.valueOf(value.get(i).getSampleNum()).multiply(value.get(i).getAccelerationMax());
                    }
                    pag = pag.add(pgai);
                }
                BigDecimal resultPgai = pag.divide(new BigDecimal(intervalZone), 4, BigDecimal.ROUND_UP);

                //N
                int N = 0;
                for (int i = dataList.getKey(); i <= collect.size(); i++) {
                    N += collect.get(i).stream().mapToInt(CtVulnerabilityEntity::getSampleNum).sum();
                }
                map.put("intensity", dataList.getKey());
                map.put("pga", resultPgai);
                map.put("N", N);
                map.put("numberSites", value.size());
                resultMap.put(dataList.getKey(), map);
            }
            return RestResponse.succeed(resultMap);
        } catch (Exception e) {
            String errorMessage = "数据异常,计算失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse importInterfaceWelding(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> read = reader.read(1, reader.getRowCount());
            List<Object> title = reader.readRow(0);
            String titleName = "[场址（流水号）, 样本数Zone(j), 最大地表加速度PGAj(g)]";
            if (!titleName.equals(title.toString())) {
                return RestResponse.fail("导入失败，请检查表头是否改动");
            }
            if (read.size() == 0) {
                return RestResponse.fail("导入失败，表格中无数据");
            }
            //数据校验
            RestResponse rs = CheckUtil.check(1, read.size(), read, titleName);
            if (rs.getCode() != 200) {
                return RestResponse.fail(rs.getMessage());
            }
            ArrayList<CtVulnerabilityImportVo> dataList = new ArrayList<>();
            read.forEach(it -> {
                CtVulnerabilityImportVo entity = new CtVulnerabilityImportVo();
                entity.setRange(Integer.valueOf(it.get(0).toString()));
                entity.setSampleNum(Integer.valueOf(it.get(1).toString()));
                entity.setAccelerationMax(new BigDecimal(it.get(2).toString()));
                dataList.add(entity);
            });
            return RestResponse.succeed(dataList);
        } catch (IOException e) {
            String errorMessage = "数据异常,导入失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public Map<String, Object> uploadTsVulnerability(String fileIds, String versionId, String userId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        shpUtils.uniformFileName(fileIds);
        ParsingResult shpData = shpUtils.getShpData(fileIds);
        //是否成功
        if (!shpData.getMessage().equals("ok")) {
            map.put("res", false);
            map.put("mess", shpData.getMessage());
        }
        List<List<Object>> shpList = shpData.getShpList();
        List<SmxTransformerSubstationEntity> tsList = new ArrayList<>();

        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            if (list.size() < 21) {
                return null;
            }
            SmxTransformerSubstationEntity entity = new SmxTransformerSubstationEntity();
            entity.setDelFlag("0");
            entity.setId(UUIDGenerator.getUUID());
            entity.setCreateUser(userId);
            entity.setCreateTime(PlatformDateUtils.getCurrentDate());

            if (!PlatformObjectUtils.isEmpty(list.get(0))) {
                entity.setGeom(list.get(0).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(1))) {
                entity.setProvince(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "省", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(2))) {
                entity.setCity(ShpAnalyticUtil.getStringVal(list.get(2).toString(), "市", false));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(3))) {
                entity.setCounty(ShpAnalyticUtil.getStringVal(list.get(3).toString(), "区县", false));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(4))) {
                entity.setTsId(ShpAnalyticUtil.getStringVal(list.get(4).toString(), "变电站编码", false));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(5))) {
                entity.setName(ShpAnalyticUtil.getStringVal(list.get(5).toString(), "变电站名称", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(6))) {
                entity.setPosition(ShpAnalyticUtil.getStringVal(list.get(6).toString(), "变电站位置", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(7))) {
                entity.setLongitude(ShpAnalyticUtil.getStringVal(list.get(7).toString(), "经度", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(8))) {
                entity.setLatitude(ShpAnalyticUtil.getStringVal(list.get(8).toString(), "纬度", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(9))) {
                entity.setTypeOfUbstation(ShpAnalyticUtil.getStringVal(list.get(9).toString(), "变电站类型", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(10))) {
                entity.setVoltageGrade(ShpAnalyticUtil.getStringVal(list.get(10).toString(), "变电站电压等级", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(11))) {
                entity.setStructureType(ShpAnalyticUtil.getStringVal(list.get(11).toString(), "主控室房屋结构类型", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(12))) {
                entity.setFortificationIntensity(ShpAnalyticUtil.getStringVal(list.get(12).toString(), "设防情况", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(13))) {
                entity.setYear(ShpAnalyticUtil.getIntegerVal(list.get(13).toString(), "建设年代", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(14))) {
                entity.setSamplesNumber(Integer.parseInt(list.get(14).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(15))) {
                entity.setPga(new BigDecimal(list.get(15).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(16))) {
                entity.setDamagesNumber(Integer.parseInt(list.get(16).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(17))) {
                entity.setSubstationTotalCost(list.get(17).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(18))) {
                entity.setEquipmentOutdoors(list.get(18).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(19))) {
                entity.setCostOfIndoorEquipment(list.get(19).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(20))) {
                entity.setCostOfBuilding(list.get(20).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(21))) {
                entity.setSite(list.get(21).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(22))) {
                entity.setType(ShpAnalyticUtil.getStringVal(list.get(22).toString(), "设备类型", true));
            }
            if (list.size() > 23 && !PlatformObjectUtils.isEmpty(list.get(23))) {
                entity.setExtends1(list.get(23).toString());
            }
            if (list.size() > 24 && !PlatformObjectUtils.isEmpty(list.get(24))) {
                entity.setExtends2(list.get(24).toString());
            }
            if (list.size() > 25 && !PlatformObjectUtils.isEmpty(list.get(25))) {
                entity.setExtends3(list.get(25).toString());
            }
            if (list.size() > 26 && !PlatformObjectUtils.isEmpty(list.get(26))) {
                entity.setExtends4(list.get(26).toString());
            }
            if (list.size() > 27 && !PlatformObjectUtils.isEmpty(list.get(27))) {
                entity.setExtends5(list.get(27).toString());
            }
            if (list.size() > 28 && !PlatformObjectUtils.isEmpty(list.get(28))) {
                entity.setExtends6(list.get(28).toString());
            }
            if (list.size() > 29 && !PlatformObjectUtils.isEmpty(list.get(29))) {
                entity.setExtends7(list.get(29).toString());
            }
            if (list.size() > 30 && !PlatformObjectUtils.isEmpty(list.get(30))) {
                entity.setExtends8(list.get(30).toString());
            }
            if (list.size() > 31 && !PlatformObjectUtils.isEmpty(list.get(31))) {
                entity.setExtends9(list.get(31).toString());
            }
            if (list.size() > 32 && !PlatformObjectUtils.isEmpty(list.get(32))) {
                entity.setExtends10(list.get(32).toString());
            }
            entity.setVersionId(versionId);
            tsList.add(entity);
        }
        boolean res = false;
        int i = 1;
        Map<String, List<SmxTransformerSubstationEntity>> tsMap = tsList.stream().collect(Collectors.groupingBy(SmxTransformerSubstationEntity::getProvince));
        for (Map.Entry<String, List<SmxTransformerSubstationEntity>> entry : tsMap.entrySet()) {
            List<SmxTransformerSubstationEntity> list = entry.getValue();
            SmxMainTableEntity mainEntity = new SmxMainTableEntity();
            mainEntity.setId(UUIDGenerator.getUUID());
            mainEntity.setYear(list.get(1).getYear());
            mainEntity.setFortification(list.get(1).getFortificationIntensity());
            mainEntity.setBusinessObject(FxfzConstants.CZT_SMX_BDZ);
            mainEntity.setCreateUser(userId);
            mainEntity.setVersionId(versionId);
            mainTableUtils.saveMainTable(mainEntity);
            for (SmxTransformerSubstationEntity entity : list) {
                entity.setSerialNumber(i);
                entity.setTableId(mainEntity.getId());
                res = tsVulnerabilityRepository.save(entity);
                i += 1;
            }
        }
        map.put("res", res);
        return map;
    }

    @Override
    public HashMap<Integer, ArrayList<String>> getDataValidation(String versionId) {
        HashMap<Integer, ArrayList<String>> map = new HashMap<>();
        SmxVersionEntity versionEntity = lifelineEngineeringRepository.getById(versionId);
        if (PlatformObjectUtils.isNotEmpty(versionEntity)) {
            List<SmxTransformerSubstationEntity> tsList = tsVulnerabilityRepository.getByVersionId(versionEntity.getId());
            int i = 1;
            for (SmxTransformerSubstationEntity entity : tsList) {
                ArrayList<String> list = ValidationProcessor.validate(entity);
                if (list.size() != 0) {
                    map.put(i, list);
                }
                i += 1;
            }
        }
        return map;
    }

    @Override
    public List<SmxTransformerSubstationEntity> getByTableId(String id) {
        return tsVulnerabilityRepository.getByTableId(id);
    }

    @Override
    public List<SmxTransformerSubstationValueVo> getValueByTsId(String id) {
        return tsVulnerabilityRepository.getValueByTsId(id);
    }

    @Override
    public void updateById(List<TsParam> tsParam) {
        tsParam.forEach(it -> {
            tsVulnerabilityRepository.updateById(it);
        });
    }
    @Override
    public RestResponse count(List<TsParam> paramList) {
        //将各元件的pga从小到达排序
        paramList.sort(Comparator.comparing(TsParam::getPga));
        paramList.forEach(it -> {
            BigDecimal pga = it.getPga();
            if (BigDecimal.valueOf(0.04).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.09)) < 0) {
                it.setRange(6);
            }
            if (BigDecimal.valueOf(0.09).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.19)) < 0) {
                it.setRange(7);
            }
            if (BigDecimal.valueOf(0.19).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.38)) < 0) {
                it.setRange(8);
            }
            if (BigDecimal.valueOf(0.38).compareTo(pga) < 1 && pga.compareTo(BigDecimal.valueOf(0.75)) < 0) {
                it.setRange(9);
            }
            if (pga.compareTo(BigDecimal.valueOf(0.75)) > -1) {
                it.setRange(10);
            }
        });

        Map<Integer, List<TsParam>> ctVulnerabilityMap = paramList.stream()
                .collect(Collectors.groupingBy(TsParam::getRange));

        Map<Integer, List<TsParam>> collect = new HashMap<>();
        int counter = 1;
        for (List<TsParam> value : ctVulnerabilityMap.values()) {
            collect.put(counter++, value);
        }
        if (collect.size() < 3) {
            return RestResponse.fail("失败!区间必须大于等于3");
        }

        ArrayList<SmxTransformerSubstationValueVo> resultList = new ArrayList<>();
        for (Map.Entry<Integer, List<TsParam>> dataList : collect.entrySet()) {
            SmxTransformerSubstationValueVo entity = new SmxTransformerSubstationValueVo();
            List<TsParam> value = dataList.getValue();
            //区间内的样本总数
            int intervalZone = value.stream().mapToInt(TsParam::getSamplesNumber).sum();
            int damagesNumber = value.stream().mapToInt(TsParam::getDamagesNumber).sum();
            BigDecimal pag = BigDecimal.valueOf(0);
            for (int i = 0; i < value.size(); i++) {
                BigDecimal pgai = BigDecimal.valueOf(0);
                for (int j = 1; j <= value.size(); j++) {
                    pgai = BigDecimal.valueOf(value.get(i).getSamplesNumber()).multiply(value.get(i).getPga());
                }
                pag = pag.add(pgai);
            }
            BigDecimal resultPgai = pag.divide(new BigDecimal(intervalZone), 4, RoundingMode.UP);
            //N
            int N = 0;
            for (int i = dataList.getKey(); i <= collect.size(); i++) {
                N += collect.get(i).stream().mapToInt(TsParam::getSamplesNumber).sum();
            }
            entity.setRange(dataList.getValue().get(0).getRange());
            entity.setPgai(resultPgai);
            entity.setSamplesAcc(N);
            entity.setSiteNum(value.size());
            entity.setRangeCount(intervalZone);
            entity.setRangeBreakCount(damagesNumber);
            resultList.add(entity);
        }

        for (int i = 0; i < resultList.size(); i++) {
            //存活概率   r(i)
            BigDecimal i1 = BigDecimal.valueOf(resultList.get(i).getRangeBreakCount())
                    .divide(BigDecimal.valueOf(resultList.get(i).getSamplesAcc()), 4, RoundingMode.HALF_UP);
            BigDecimal r = BigDecimal.valueOf(1).subtract(i1);
            resultList.get(i).setRil(r.setScale(4, RoundingMode.HALF_UP));

            //累积失效概率  R
            if (i == 0) {
                resultList.get(i).setRir(resultList.get(i).getRil().setScale(4, RoundingMode.HALF_UP));
            } else {
                resultList.get(i).setRir(resultList.get(i).getRil()
                        .multiply(resultList.get(i - 1).getRir()).setScale(4, RoundingMode.HALF_UP));
            }
            //累计失效概率  F
            resultList.get(i).setFi(BigDecimal.valueOf(1).subtract(resultList.get(i).getRir()).setScale(4, RoundingMode.HALF_UP));
            resultList.get(i).setFiCorrect(BigDecimal.valueOf(1).subtract(resultList.get(i).getRir()).setScale(4, RoundingMode.HALF_UP));
        }
        return RestResponse.succeed(resultList);
    }

    @Override
    public void delValueByTsId(String tsId) {
        tsVulnerabilityRepository.delValueByTsId(tsId);
    }

    @Override
    public void saveResult(List<TsValueParam> valueParam,String tsId) {
        for (TsValueParam tsValueParam : valueParam) {
            tsValueParam.setTsId(tsId);
            tsValueParam.setId(UUIDGenerator.getUUID());
            tsValueParam.setDelFlag("0");
            tsVulnerabilityRepository.saveResult(tsValueParam);
        }
    }
}
